<?php

namespace App\Listeners;

use DateTime;
use Exception;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Log;

class QueryListener
{
    public function handle(QueryExecuted $event)
    {
        try {
            // if (env('APP_DEBUG') == true) {
            $sql = str_replace("?", "'%s'", $event->sql);
            foreach ($event->bindings as $i => $binding) {
                if ($binding instanceof DateTime) {
                    $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                } else {
                    if (is_string($binding)) {
                        $event->bindings[$i] = "$binding";
                    }
                }
            }
            $log = vsprintf($sql, $event->bindings);
            $log = str_replace("\\", "", $log);
            $log = $log . '  [ cost: ' . $event->time . 'ms ] ';
            Log::channel('sql_query')->info($log);
            // }
        } catch (Exception $e) {
            Log::error($e->getMessage());
        }
    }
}
